package com.swdegao.iot.netty.server.qianbaotonghandler;

import com.alibaba.fastjson.JSON;
import com.swdegao.iot.SwdegaoIotMgtServerApplication;
import com.swdegao.iot.netty.entity.*;
import com.swdegao.iot.netty.utils.HttpClientUtil;
import com.swdegao.iot.netty.utils.RedisUtils;
import com.swdegao.iot.netty.utils.RocketMQUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 *
 * 用于存储数据包、更新redis中数据
 *
 * @Author:只会走路的小鸟
 * @Date: Created in 8:20 2018\10\29 0001
 */
public class QianBaoTong_PushMessgaeHandler extends SimpleChannelInboundHandler<CallBackData> {

	static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	@Autowired
    private MyProps myProps = SwdegaoIotMgtServerApplication.getBean(MyProps.class);
	@Autowired
    private RedisUtils redisUtils = SwdegaoIotMgtServerApplication.getBean(RedisUtils.class);
	@Autowired
    private RocketMQUtils rocketMQUtils = SwdegaoIotMgtServerApplication.getBean(RocketMQUtils.class);
	// 定义一个全局的记录器，通过LoggerFactory获取
	private final static Logger logger = LoggerFactory.getLogger(QianBaoTong_PushMessgaeHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext arg0, CallBackData msg) throws Exception {

		String imei,topic,tag;
		try {
			if(null != msg.getImei() && !"".equals(msg.getImei())){
//				rocketMQUtils.sendMessage(msg.getImei(),msg.getTopic(),msg.getTag(), rocketMQUtils.getCallBackBean(msg));

				if(!redisUtils.hmhave(Parameter.imei_info,msg.getImei())){
					ImeiInfo imeiInfo = new ImeiInfo();
					imeiInfo.setOnlineLastTime(System.currentTimeMillis());
					imeiInfo.setOnlineStatus("1");
					imeiInfo.setcType(Parameter.communication_tcp);
					imeiInfo.setImei(msg.getImei());
					imeiInfo.setOutTime(Parameter.outtime_hear);
					imeiInfo.setHeartbeat_registered_num(0);
					imeiInfo.setHeartbeat_delay_num(0);
					imeiInfo.setHeartbeat_cycle(Parameter.heartbeat_cycle);
					redisUtils.hmSet(Parameter.imei_info, msg.getImei(), JSON.toJSONString(imeiInfo));
				}


//				//有回调逻辑
//				imei = msg.getImei();
//				Integer callbackType = myProps.getCallbackType();
//				topic = (null == msg.getTopic() || "".equals(msg.getTopic()))? "": msg.getTopic();
//				switch (callbackType) {
//				case 0://server中处理http推送
//					rocketMQUtils.doSendHttpPost(msg);
//					break;
//				case 1://1：center中处理http推送
//					redisUtils.lPush(imei+Parameter.imei_callbackurl,JSON.toJSONString(msg));//存储所有updata数据
//					break;
//				case 2://1：回调数据放到redis的dggprs_callback_imei中
//					//redisUtils.lPush(Parameter.topic_redis + Parameter.topic_callbackurl + imei,JSON.toJSONString(rocketMQUtils.getCallBackBean(msg)));//存储所有updata数据
//					//2022-02-09 其他设备数据进入redis，存储不同的key,json与center http 推送数据相同
//
//					if(topic.equals(myProps.getTopicOther())){
//						redisUtils.lPush(Parameter.topic + Parameter.topic_callbackurl + imei,JSON.toJSONString(msg));//存储所有updata数据
//					}else{
//						redisUtils.lPush(Parameter.topic_redis + Parameter.topic_callbackurl + imei,JSON.toJSONString(rocketMQUtils.getCallBackBean(msg)));//存储所有updata数据
//					}
//					break;
//				case 3://2：MQ消息订阅发布
//					try {
//						topic = (null == msg.getTopic() || "".equals(msg.getTopic()))? Parameter.topic : msg.getTopic();
//						tag = (null == msg.getTag() || "".equals(msg.getTag()))? Parameter.tag : msg.getTag();
//						rocketMQUtils.sendMessage(imei,topic,tag, rocketMQUtils.getCallBackBean(msg));
//					} catch (Exception e) {
//						// TODO: handle exception
//						logger.error(e.getMessage());
//					}
//
//					break;
//				case 4://1：center中处理http推送
//					//老系统停用，注释掉redis的回调key
////					if(!topic.equals(myProps.getTopicOther())){
////						redisUtils.lPush(imei+Parameter.imei_callbackurl,JSON.toJSONString(msg));//存储所有updata数据
////					}
//					//redis 消费同时进行
//					topic = (null == msg.getTopic() || "".equals(msg.getTopic()))? "": msg.getTopic();
//					if(topic.equals(myProps.getTopicOther())){
//						redisUtils.lPush(Parameter.topic + Parameter.topic_callbackurl + imei,JSON.toJSONString(msg));//存储所有updata数据
//					}else{
//						redisUtils.lPush(Parameter.topic_redis + Parameter.topic_callbackurl + imei,JSON.toJSONString(rocketMQUtils.getCallBackBean(msg)));//存储所有updata数据
//					}
//					break;
//				default:
//					break;
//				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}


		//doSendHttpPostCallback(imei);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
		Channel incoming = ctx.channel();
		logger.info("client " + incoming.remoteAddress() + "异常" + cause.getMessage());
		// 当出现异常就关闭连接
		cause.printStackTrace();
		// ctx.close();
	}
	private void doSendHttpPostCallback(String imei){

		List<String> keylist = new ArrayList<String>();
		// 1获取redis缓存中所有的keys
		Set<String> keys = redisUtils.getAllKeys();
		// 2、遍历keys集合，找出上报数据的list
		for (String key : keys) {
			if (key.endsWith(Parameter.imei_callbackurl)) {
				keylist.add(key);
			}
		}
		// 3、遍历keylist,获取value
		for (String key : keylist) {
			// 获取redis缓存中对应key的list长度
			String imei_ = key.substring(0,key.indexOf("_"));
			// 根据key值获取对应value的需要同步的数据
			int length = redisUtils.getLength(key);
			if(key.indexOf(Parameter.imei_callbackurl)!=-1 && imei_.length() > 10 && imei_.equals(imei)) {
				List<Object> list = redisUtils.lRange(key, 0, -1);
				redisUtils.remove(key);
				// 将数据转化为实体类对象
				for (Object object : list) {
					CallBackData callBackData = JSON.parseObject(object.toString(), CallBackData.class);
					if(callBackData.getCallbackNum()<2){
						String flag = doSendHttpPostC(callBackData);
						if(null == flag){
							callBackData.setCallbackNum(callBackData.getCallbackNum() + 1);
							redisUtils.lPush(imei+Parameter.imei_callbackurl,JSON.toJSONString(callBackData));//存储所有updata数据
						}
					}else{
						redisUtils.lPush(imei+Parameter.imei_callbackurl,JSON.toJSONString(callBackData));//存储所有updata数据
					}

				}

				//刷新redis缓存
//				rs.lTrim(key, length-2, -1);
			}
		}

	}
	private String doSendHttpPostC(CallBackData callBackData){
		String flag = null;
		String url = callBackData.getUrl();
		if("".equals(url))url = myProps.getMycallbackurl();
		long nowtime = System.currentTimeMillis();
		String imei = callBackData.getImei();
		PushMessage pusmessage = new PushMessage();
		pusmessage.setImei(imei);
		pusmessage.setServiceId("");
		pusmessage.setPushTime(nowtime);

		// 从msg中获取updata
		List<UpData> list = new ArrayList<UpData>();
		UpData updata = new UpData();
		updata.setCreatetime(nowtime);
		updata.setImei(imei);


		//logger.info(imei+"###########################" + Hex.encodeHexString(receiveMsgBytes));
		updata.setUpData(callBackData.getUpData());
		list.add(updata);
		pusmessage.setUpDataList(list);
		//logger.error(imei+"Parametercall_back_url"+url);
		try {
			flag = HttpClientUtil.sendHttpPostJson(url, JSON.toJSONString(pusmessage));
		} catch (Exception e) {
			// TODO: handle exception
		}

		return flag;

	}
	private void doSendHttpPost(HandlerMessage msg,String url){
		if("".equals(url))url = Parameter.call_back_url;
		long nowtime = System.currentTimeMillis();
		String imei = msg.getImei();
		PushMessage pusmessage = new PushMessage();
		pusmessage.setImei(imei);
		pusmessage.setServiceId("");
		pusmessage.setPushTime(nowtime);

		// 从msg中获取updata
		List<UpData> list = new ArrayList<UpData>();
		UpData updata = new UpData();
		updata.setCreatetime(nowtime);
		updata.setDownDataId(msg.getDownDataId());
		updata.setImei(imei);

		byte[] receiveMsgBytes = new byte[msg.getRecevieMsg().capacity()];
		msg.getRecevieMsg().getBytes(msg.getRecevieMsg().readerIndex(), receiveMsgBytes);

		//logger.info(imei+"###########################" + Hex.encodeHexString(receiveMsgBytes));
		updata.setUpData(Hex.encodeHexString(receiveMsgBytes).toUpperCase());
		list.add(updata);
		pusmessage.setUpDataList(list);
		//logger.error(imei+"Parametercall_back_url"+url);
		HttpClientUtil.sendHttpPostJson(url, JSON.toJSONString(pusmessage));

	}

}
